package com.ddx.service.impl;


import com.ddx.check.CheckOrderParamValidate;
import com.ddx.common.enums.ErrorCode;
import com.ddx.common.enums.OrderStatus;
import com.ddx.common.enums.ResultType;
import com.ddx.common.exception.BusinessException;
import com.ddx.dao.ShoppingOrderMapper;
import com.ddx.dao.ShoppingPayFlowMapper;
import com.ddx.dao.UserMapper;
import com.ddx.dto.ShoppingOrderVo;
import com.ddx.pay.*;
import com.ddx.pojo.ShoppingOrder;
import com.ddx.pojo.ShoppingPayFlow;
import com.ddx.pojo.ShoppingPayFlowWithBLOBs;
import com.ddx.pojo.User;
import com.ddx.service.IUserPayService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author dudianbo
 * @ClassName: ${CLASSNAME}
 * @Description: ${DESCRIPTION}
 * @date 2018/12/15
 */
@Service
public class UserPayServiceImpl implements IUserPayService {
    private static Logger logger = LoggerFactory.getLogger(UserPayServiceImpl.class);
    @Autowired
    WeixinPay weixinPay;
    @Autowired
    ShoppingOrderMapper shoppingOrderMapper;
    @Autowired
    ShoppingPayFlowMapper shoppingPayFlowMapper;
    @Autowired
    UserMapper userMapper;
    /**
     * api_key
     */
    @Value("${API_KEY}")
    private  String API_KEY;
    /**
     * 微信app支付
     * @param shoppingOrderVo
     */
    @Override
    public Map<String,String> WeChatAppPay(ShoppingOrderVo shoppingOrderVo, String ip) throws Exception{
        logger.info("微信app支付接口参数txMailDemandDto={},ip={}",shoppingOrderVo,ip);
        // 验证参数
        CheckOrderParamValidate.weixinPayMailDemand(shoppingOrderVo);
        // 查询该订单号是否存在
        ShoppingOrder shoppingOrder = shoppingOrderMapper.selectOrderByOrderId(shoppingOrderVo.getOrderId());
        if(shoppingOrder == null){
            throw new BusinessException(ErrorCode.BUSSINESS_ERROR_201);
        }
        //获取openid
        WeChatRequestPayDto weChatRequestPayDto=new WeChatRequestPayDto();
        weChatRequestPayDto.setTotal_fee((shoppingOrder.getPtotal().movePointRight(2)).toString());
        weChatRequestPayDto.setOut_trade_no(shoppingOrder.getOrderId());
        weChatRequestPayDto.setTrade_type("APP");
        weChatRequestPayDto.setSpbill_create_ip(ip);
        weChatRequestPayDto.setBody("多艺直播");
        logger.info("获取客户端ip={}",ip);
        WeChatPayDto weChatPayDto=weixinPay.payUnifiedorder(weChatRequestPayDto);
        if(StringUtils.isBlank(weChatPayDto.getPrepayid())){
            throw new BusinessException(ErrorCode.BUSSINESS_ERROR_203,weChatPayDto.getErrmsg());
        }
        Map<String,String> map=new HashMap<>();
        map.put("appid",weChatPayDto.getAppId());
        map.put("partnerid",weChatPayDto.getPartnerid());
        map.put("prepayid",weChatPayDto.getPrepayid());
        map.put("package","Sign=WXPay");
        map.put("noncestr",UUID.randomUUID().toString().replace("-", ""));
        map.put("timestamp",String.valueOf(System.currentTimeMillis()/1000));
        String sign = SignatureUtil.generateSign(map, API_KEY);
        map.put("sign",sign);
        ShoppingPayFlowWithBLOBs shoppingPayFlowWithBLOBs=new ShoppingPayFlowWithBLOBs();
        shoppingPayFlowWithBLOBs.setOrderId(shoppingOrderVo.getOrderId());
        shoppingPayFlowWithBLOBs.setAmount(shoppingOrder.getPtotal());
        shoppingPayFlowWithBLOBs.setPayType("1");
        shoppingPayFlowWithBLOBs.setFeeType("2");
        shoppingPayFlowWithBLOBs.setThirdPartyNo(weChatPayDto.getTradeno());
        shoppingPayFlowWithBLOBs.setDealStatus(ResultType.PROCESSING.getCode());
        shoppingPayFlowWithBLOBs.setUserId(shoppingOrderVo.getUserId());
        shoppingPayFlowWithBLOBs.setBeforeSendRecord(JsonUtil.toJSONString(weChatRequestPayDto));
        shoppingPayFlowMapper.insertSelective(shoppingPayFlowWithBLOBs);
        return map;
    }
    /**
     * 保证金支付
     * @param shoppingOrderVo
     */
    @Override
    public Map<String,String> bondPay(ShoppingOrderVo shoppingOrderVo, String ip) throws Exception{
        logger.info("微信app支付接口参数txMailDemandDto={},ip={}",shoppingOrderVo,ip);
        // 验证参数
        CheckOrderParamValidate.weixinPayMailDemand(shoppingOrderVo);
        //获取openid
        WeChatRequestPayDto weChatRequestPayDto=new WeChatRequestPayDto();
        weChatRequestPayDto.setTotal_fee((shoppingOrderVo.getAmount().movePointRight(2)).toString());
        weChatRequestPayDto.setOut_trade_no(shoppingOrderVo.getOrderId());
        weChatRequestPayDto.setTrade_type("APP");
        weChatRequestPayDto.setSpbill_create_ip(ip);
        weChatRequestPayDto.setBody("多艺直播");
        logger.info("获取客户端ip={}",ip);
        WeChatPayDto weChatPayDto=weixinPay.payUnifiedorder(weChatRequestPayDto);
        if(StringUtils.isBlank(weChatPayDto.getPrepayid())){
            throw new BusinessException(ErrorCode.BUSSINESS_ERROR_203,weChatPayDto.getErrmsg());
        }
        Map<String,String> map=new HashMap<>();
        map.put("appid",weChatPayDto.getAppId());
        map.put("partnerid",weChatPayDto.getPartnerid());
        map.put("prepayid",weChatPayDto.getPrepayid());
        map.put("package","Sign=WXPay");
        map.put("noncestr",UUID.randomUUID().toString().replace("-", ""));
        map.put("timestamp",String.valueOf(System.currentTimeMillis()/1000));
        String sign = SignatureUtil.generateSign(map, API_KEY);
        map.put("sign",sign);
        ShoppingPayFlowWithBLOBs shoppingPayFlowWithBLOBs=new ShoppingPayFlowWithBLOBs();
        shoppingPayFlowWithBLOBs.setOrderId(shoppingOrderVo.getOrderId());
        shoppingPayFlowWithBLOBs.setAmount(shoppingOrderVo.getAmount());
        shoppingPayFlowWithBLOBs.setPayType("1");
        shoppingPayFlowWithBLOBs.setFeeType("1");
        shoppingPayFlowWithBLOBs.setThirdPartyNo(weChatPayDto.getTradeno());
        shoppingPayFlowWithBLOBs.setDealStatus(ResultType.PROCESSING.getCode());
        shoppingPayFlowWithBLOBs.setUserId(shoppingOrderVo.getUserId());
        shoppingPayFlowWithBLOBs.setBeforeSendRecord(JsonUtil.toJSONString(weChatRequestPayDto));
        shoppingPayFlowMapper.insertSelective(shoppingPayFlowWithBLOBs);
        return map;
    }
    @Override
    public MchOrderInfoResult callBack(ShoppingOrderVo shoppingOrderVo) throws Exception {
        logger.info("微信app支付返回结果接口参数shoppingOrderVo={}",shoppingOrderVo);
        // 验证参数
        CheckOrderParamValidate.weixinPayMailDemand(shoppingOrderVo);
        // 查询该订单号是否存在
        ShoppingOrder shoppingOrder = shoppingOrderMapper.selectOrderByOrderId(shoppingOrderVo.getOrderId());
        if(shoppingOrder == null){
            throw new BusinessException(ErrorCode.BUSSINESS_ERROR_201);
        }
        MchOrderInfoResult mchOrderInfoResult=weixinPay.payOrderquery(shoppingOrderVo.getOrderId());
        logger.info("微信支付查询返回结果mchOrderInfoResult={}",mchOrderInfoResult);
        if("SUCCESS".equals(mchOrderInfoResult.getTrade_state())){
            ShoppingPayFlowWithBLOBs record=new ShoppingPayFlowWithBLOBs();
            record.setReturnSendRecord(JsonUtil.toJSONString(mchOrderInfoResult));
            record.setOrderId(shoppingOrderVo.getOrderId());
            record.setDealStatus(ResultType.SUCCESS.getCode());
            if(StringUtils.isNotBlank(mchOrderInfoResult.getTrade_state_desc())) {
                record.setMessage(new String(mchOrderInfoResult.getTrade_state_desc().getBytes("iso8859-1"), "utf-8"));
            }
            record.setTimeEnd(mchOrderInfoResult.getTime_end());
            shoppingPayFlowMapper.updateByOrderId(record);
            ShoppingOrder update=new ShoppingOrder();
            update.setOrderId(shoppingOrderVo.getOrderId());
            update.setStatus(OrderStatus.DAIFAHUO.getValue());
            shoppingOrderMapper.updateByOrderId(update);
        }else if("NOTPAY".equals(mchOrderInfoResult.getTrade_state())||"FAIL".equals(mchOrderInfoResult.getTrade_state())){
            ShoppingPayFlowWithBLOBs record=new ShoppingPayFlowWithBLOBs();
            record.setReturnSendRecord(JsonUtil.toJSONString(mchOrderInfoResult));
            record.setOrderId(shoppingOrderVo.getOrderId());
            record.setDealStatus(ResultType.FAILED.getCode());
            if(StringUtils.isNotBlank(mchOrderInfoResult.getTrade_state_desc())) {
                record.setMessage(new String(mchOrderInfoResult.getTrade_state_desc().getBytes("iso8859-1"), "utf-8"));
            }
            record.setTimeEnd(mchOrderInfoResult.getTime_end());
            shoppingPayFlowMapper.updateByOrderId(record);
        }
        return mchOrderInfoResult;
    }

    @Override
    public MchOrderInfoResult bondCallBack(ShoppingOrderVo shoppingOrderVo) throws Exception {
        logger.info("微信app保证金支付返回结果接口参数shoppingOrderVo={}",shoppingOrderVo);
        // 验证参数
        CheckOrderParamValidate.weixinPayMailDemand(shoppingOrderVo);
        MchOrderInfoResult mchOrderInfoResult=weixinPay.payOrderquery(shoppingOrderVo.getOrderId());
        logger.info("微信支付查询返回结果mchOrderInfoResult={}",mchOrderInfoResult);
        if("SUCCESS".equals(mchOrderInfoResult.getTrade_state())){
            ShoppingPayFlowWithBLOBs record=new ShoppingPayFlowWithBLOBs();
            record.setReturnSendRecord(JsonUtil.toJSONString(mchOrderInfoResult));
            record.setOrderId(shoppingOrderVo.getOrderId());
            record.setDealStatus(ResultType.SUCCESS.getCode());
            record.setThirdPartyNo(mchOrderInfoResult.getTransaction_id());
            if(StringUtils.isNotBlank(mchOrderInfoResult.getTrade_state_desc())) {
                record.setMessage(new String(mchOrderInfoResult.getTrade_state_desc().getBytes("iso8859-1"), "utf-8"));
            }
            record.setTimeEnd(mchOrderInfoResult.getTime_end());
            shoppingPayFlowMapper.updateByOrderId(record);
            User updateUser=new User();
            updateUser.setId(Integer.parseInt(shoppingOrderVo.getUserId()));
            updateUser.setIsBond(1);
            userMapper.updateByPrimaryKeySelective(updateUser);
        }else if("NOTPAY".equals(mchOrderInfoResult.getTrade_state())||"FAIL".equals(mchOrderInfoResult.getTrade_state())){
            ShoppingPayFlowWithBLOBs record=new ShoppingPayFlowWithBLOBs();
            record.setReturnSendRecord(JsonUtil.toJSONString(mchOrderInfoResult));
            record.setOrderId(shoppingOrderVo.getOrderId());
            record.setDealStatus(ResultType.FAILED.getCode());
            if(StringUtils.isNotBlank(mchOrderInfoResult.getTrade_state_desc())) {
                record.setMessage(new String(mchOrderInfoResult.getTrade_state_desc().getBytes("iso8859-1"), "utf-8"));
            }
            record.setTimeEnd(mchOrderInfoResult.getTime_end());
            shoppingPayFlowMapper.updateByOrderId(record);
        }
        return mchOrderInfoResult;
    }

}
